'''
Created on Nov 26, 2012

@author: shraybansal
'''

import os
import cPickle as pickle
from featureset import gesture
from DistanceRow import DistanceRow
from utils import readAllPickles

def combineGestures(gest1 , gest2):
    if (gest1.getGestureName() == gest2.getGestureName()):
        naNorm = gest1.returnaNorm() + gest2.returnaNorm()
        naX = gest1.returnaX() + gest2.returnaX()
        naY = gest1.returnaY() + gest2.returnaY()
        naZ = gest1.returnaZ() + gest2.returnaZ()
        ngX = gest1.returngX() + gest2.returngX()
        ngY = gest1.returngY() + gest2.returngY()
        ngZ = gest1.returngZ() + gest2.returngZ()
        ntimes = gest1.returnTimes() + gest2.returnTimes()
        nfeature = (naNorm , naX , naY , naZ , ngX , ngY , ngZ , ntimes)
        return gesture(gest1.getGestureName() , nfeature)
    else:
        print "Cannot combine gestures of different names! " + gest1.getGestureName() + " " + gest2.getGestureName()
        return None

#def readAllPickles():
#    """
#    return type - dictionary
#    argument - none
#    """
#    path = os.getcwd() + '/pickles'
#    gestureSet = {}
#    for fileName in os.listdir(path):
#        if (os.path.splitext(fileName)[1] == ".pkl"):
#            pklFile = open(path + '//' + fileName, 'rb')
#            gestureNameFull = pickle.load(pklFile)
#            noGestures = pickle.load(pklFile)
#            gest = pickle.load(pklFile)
#            if gest.getGestureName() in gestureSet:
#                oldGesture = gestureSet[gest.getGestureName()]
#                del gestureSet[gest.getGestureName()]
#                ngest = combineGestures(gest , oldGesture)
#                gestureSet[ngest.getGestureName()] = ngest
#            else:
#                gestureSet[gest.getGestureName()] = gest
#    return gestureSet


if __name__ == '__main__':


    """Read all gestures from pickles"""
    gestSet = readAllPickles()
    
   
        
    gestureNames = ['Orient', 'Slap', 'Triangle', 'Window_Open', 'Window_Close', 'Fire_On', 'Fire_Off', 'Throw_Money', 'Swing_Phone',
                    'W', 'Tap_Phone', 'Multi_Finger_Snap', 'Flick_Air', 'Door_Open', 'Door_Close']
#    gestureRemov = ['Orient', 'Slap', 'Triangle', 'Window_Open', 'Window_Close', 'Fire_On', 'Fire_Off', 'Throw_Money', 'Swing_Phone',
#                    'W', 'Tap_Phone', 'Multi_Finger_Snap', 'Flick_Air','Door_Open']
#    
#    for testName in gestureRemov:
#        del gestSet[testName]
#    gestureScores = [0.703, 0.891, 0.632, 0.694, 0.382, 0.312, 0.657, 0.805, 0.885, 0.598, 0.162, 0.776, 0.688, 1, 0.678]
    
#    """Apply user-scores to read gestures"""
#    i = 0
#    for name in gestureNames:
#        gest = gestSet[name]
#        gest.setScore(gestureScores[i])
#        gestSet[name] = gest
#        i += 1
#    gb=gestSet['Orient'].returnaNorm()
#    for g in gb:
#        print g
     
    """Display gestures read and the no. of examples"""
    for gestName in gestSet.keys():
        print gestSet[gestName].getGestureName()
        print gestSet[gestName].returnaNorm().__len__()
#        print gestSet[gestName].returnScore()
        
        
    """Computing the distance(DTW) from each gesture example to every other one
        the different distances computed are acceleration norm, acceleration(x,y,z), angular vel(x,y,z) and both
        so 4 different files generated each corresponding to a diff feature vector""" 
    
    dist_mat = []
    ges_left = []
    for gestName in gestSet.keys():
        ges_left.append(gestName)
#    del ges_left[0]
    print ges_left
    
    out_path = os.getcwd() + '/DTW_dist_pickles'
    fileName = 'AccNorm_Dist_proper.pkl'
    pickly = open(out_path+'//'+fileName, 'wb')
    
    """Iterate through all gesture names"""
    for g in range(len(gestSet.keys())):
        gestName = ges_left[g]
        ex_feats = gestSet[gestName].returnaNorm()                
        """Iterate through each of the example"""
        for i in range(gestSet[gestName].returnaNorm().__len__()):
            print "-------------starting Gesture=", gestName, 'example-',i
            ex_feat = ex_feats[i]
            
            for gC in range(len(gestSet.keys())):
                if gC>=g:
                    gestNameC  = ges_left[gC]
                    query_feats= gestSet[gestNameC].returnaNorm()
                    print '*****comparin to Gesture-', gestNameC
                    
                    for iC in range(gestSet[gestNameC].returnaNorm().__len__()):
                        query_feat = query_feats[iC]
                        if gC==g and iC==i:
                            sam_row = DistanceRow(gestName, i, gestNameC, iC)
                            sam_row.findAccNormDist([],[])
                            if not sam_row.returnDist()==0:
                                print "error", sam_row.returnAlla()
                                exit();
                            else:
                                dist_mat.append(sam_row)
                                print i
                        elif not(gC==g) or iC>i:
                            new_ro1 = DistanceRow(gestName, i, gestNameC, iC)
                            new_ro2 = DistanceRow(gestNameC, iC, gestName, i)
                            new_ro1.findAccNormDist(ex_feat, query_feat)
                            new_ro2.setDist(new_ro1.returnDist())
                            dist_mat.append(new_ro1)
                            dist_mat.append(new_ro2)
    pickle.dump(dist_mat, pickly)
    pickly.close()     
